//
//  EightFoodManager.m
//  DongChiDaChiProject1
//
//  Created by lanou3g on 15/10/27.
//  Copyright © 2015年 com.lanou3g. All rights reserved.
//

#import "EightFoodManager.h"
#import "EightFoodModel.h"
@interface EightFoodManager ()
@property (nonatomic, strong)NSMutableArray *dataArray;
@end
@implementation EightFoodManager

// 声明单例
+ (instancetype)shareManager
{
    static EightFoodManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[[self class] alloc] init];
        
    });
    return manager;
}
// // 数据请求 带有两个数组参数 一个接口 和 接口的动态数据P
- (void)requestDataForReloadWithBlock:(void (^)(NSMutableArray *))block url:(NSString *)url pNumber:(NSInteger)pNumber
{
    // 创建子线程 做数据解析
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        //创建请求
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:30.0];
        // 设置方法
        [request setHTTPMethod:@"GET"];
        // 7.0 新添加方法
        // 创建 config
        NSURLSessionConfiguration *config = [NSURLSessionConfiguration ephemeralSessionConfiguration];
        // 根据 config 创建 session
        NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
        // 根据他们创建 datadusk
        NSURLSessionDataTask *dataDusk = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            if (!data) {
                return;
            }
           // NSLog(@"6666666666666666666 = %@", data);
            //在这里请求数据
            NSDictionary *rootDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
             self.dataArray = [NSMutableArray array];
//            NSArray *array12 = [rootDic valueForKey:@"results"];
            NSArray *array12 = rootDic[@"results"];
            // 在数组里遍历
            for (NSDictionary *dic12 in array12) {
                // 创建model
                EightFoodModel *model = [[EightFoodModel alloc] init];
                [model setValuesForKeysWithDictionary:dic12];//保存到 model 中
                // 然后把 model 保存到数组中 首先要初始化数组
                [self.dataArray addObject:model];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                //回调主线程
                block(self.dataArray);
            });
            
        }];
        [dataDusk resume];
        
    });
}
// 通过下角标进行结果回调
- (EightFoodModel *)getEightFoodModelAtIndex:(NSInteger)index
{
    if (self.dataArray.count <= index) {
        return nil;
    }
    EightFoodModel *model = self.dataArray[index];
    return model;
}

// 获取有多少条数据
- (NSInteger)getDataArrayCount
{
    return self.dataArray.count;
}


@end

